import React, { useRef, useState, useEffect } from 'react'
import { Modal, Form, Input, Button, Upload, message, Select, Radio, DatePicker } from 'antd'
import { UploadOutlined } from '@ant-design/icons'
import { awaitWrap, getUploadPropsFn, strToNum } from '@js/tool'
import { submitFiles } from '@js/request'
import Editor from '@components/Editor'
import { addRequest, getRequest, updateRequest } from './ajax'
import style from './Index.module.less'
import moment from 'moment'

const { Item } = Form
const { TextArea } = Input
const options = ['司法厅', '仲裁机构', '当事人', '仲裁员'].map(li => ({ label: li, value: li }))

async function getHandle (id, formRef, setThumbnail, setFileList) {
  const c = formRef.current
  const h = message.loading('加载中')
  const [e, d] = await awaitWrap(getRequest(id))
  h()
  if (e === null && d !== null) {
    if (d.thumbnail instanceof Object) {
      setThumbnail([d.thumbnail].map(li => {
        li.name = li.original_filename || li.filename
        return li
      }))
    }
    if (d.file instanceof Array && d.file.length > 0) {
      setFileList(d.file.map(li => {
        li.name = li.original_filename || li.filename
        return li
      }))
    }
    if (typeof d.visible_type === 'string' && d.visible_type.length > 0) {
      d.visible_type = d.visible_type.split(',').filter(li => li)
    } else {
      d.visible_type = []
    }
    if (typeof d.visible_structure === 'string' && d.visible_structure.length > 0) {
      d.visible_structure = d.visible_structure.split(',').filter(li => li)
    } else {
      d.visible_structure = []
    }
    d.expiry_datetime = strToNum(d.expiry_datetime)
    d.release_datetime = strToNum(d.release_datetime)
    if (d.expiry_datetime) {
      d.expiry_datetime = moment(d.expiry_datetime * 1000)
    }
    if (d.release_datetime) {
      d.release_datetime = moment(d.release_datetime * 1000)
    }
    console.log(d)
    c.setFieldsValue(d)
  }
}

async function submitHandle (form, thumbnail, fileList, structureMap, callback) {
  const hide = message.loading('提交中', 120)
  let fn = addRequest
  if (form.id) {
    fn = updateRequest
  }
  const keys = Object.keys(form)
  keys.forEach(k => {
    if (!form[k]) {
      form[k] = null
    }
  })
  if (thumbnail.length > 0) {
    const [e, d] = await awaitWrap(submitFiles(thumbnail))
    if (e) {
      hide()
    }
    form.thumbnailid = d
  }
  if (fileList.length > 0) {
    const [e, d] = await awaitWrap(submitFiles(fileList))
    if (e) {
      hide()
    }
    form.fileid = d
  }
  delete form.file
  delete form.thumbnail
  if (form.visible_type instanceof Array && form.visible_type.length) {
    form.visible_type = form.visible_type.join(',')
  } else {
    form.visible_type = null
  }
  if (form.visible_structure instanceof Array && form.visible_structure.length) {
    form.visible_structure = form.visible_structure.join(',')
  } else {
    form.visible_structure = null
  }
  if (form.release_datetime && form.release_datetime instanceof moment) {
    form.release_datetime = Math.floor(form.release_datetime.valueOf() / 1000)
  }
  if (form.expiry_datetime && form.expiry_datetime instanceof moment) {
    form.expiry_datetime = Math.floor(form.expiry_datetime.valueOf() / 1000)
  }
  const [e] = await awaitWrap(fn(form))
  hide()
  if (e === null) {
    callback()
  }
}

function Main ({ visible, data, structures, structureMap, hide = () => {}, refreshFn = () => {} }) {
  const formRef = useRef(null)
  const [thumbnail, setThumbnail] = useState([])
  const [fileList, setFileList] = useState([])
  useEffect(() => {
    const c = formRef.current
    if (c) {
      if (visible) {
        if (data) {
          getHandle(data.id, formRef, setThumbnail, setFileList)
        }
      } else {
        setFileList([])
        c.resetFields()
      }
    }
  }, [visible, data, formRef])
  return (
    <Modal width='1000px' open={visible} title={`${data ? '编辑公函' : '新增公函'}`} onCancel={() => { hide() }} onOk={() => formRef.current.submit()} maskClosable={false}>
      <Form ref={formRef} labelCol={{ flex: '80px' }} initialValues={{ status: '发布' }} onFinish={(d) => { submitHandle(d, thumbnail, fileList, structureMap, () => { refreshFn(); hide() }) }}>
        <Item name='id' noStyle><span /></Item>
        <Item label='标题' name='title' rules={[{ required: true, message: '标题不能为空' }]}>
          <Input placeholder='请输入' allowClear />
        </Item>
        <Item label='作者' name='author'>
          <Input placeholder='请输入' allowClear />
        </Item>
        <Item label='简介' name='summary'>
          <TextArea placeholder='请输入' allowClear />
        </Item>
        <Item label='链接' name='url'>
          <Input placeholder='请输入' allowClear />
        </Item>
        <Item label='可见机构' name='visible_structure'>
          <Select placeholder='请选择' options={structures} mode='multiple' allowClear />
        </Item>
        <Item label='可见类型' name='visible_type'>
          <Select placeholder='请选择' options={options} mode='multiple' allowClear />
        </Item>
        <Item label='状态' name='status'>
          <Radio.Group>
            <Radio value='发布'>发布</Radio>
            <Radio value='草稿'>未发布</Radio>
          </Radio.Group>
        </Item>
        <Item label='发布日期' name='release_datetime'>
          <DatePicker placeholder='请选择' showTime allowClear />
        </Item>
        <Item label='失效日期' name='expiry_datetime'>
          <DatePicker placeholder='请选择' showTime allowClear />
        </Item>
        <Item label='缩略图' name='thumbnail'>
          <Upload {...getUploadPropsFn.call(this, formRef, '.png,.jpg,.jpeg', thumbnail, setThumbnail)}>
            {
              thumbnail.length < 1 && (
                <div className={style.upload}>
                  <Button>
                    <UploadOutlined /> 上传文件
                  </Button>
                  <div className={style.sub}>支持扩展名：.png,.jpg,.jpeg，图片尺寸：100 x 70 像数，最多上传1个文件</div>
                </div>
              )
            }
          </Upload>
        </Item>
        <Item name='file' label='附件'>
          <Upload {...getUploadPropsFn.call(this, formRef, '.png,.jpg,.jpeg', fileList, setFileList)}>
            <div className={style.upload}>
              <Button>
                <UploadOutlined /> 上传文件
              </Button>
              <div className={style.sub}>支持扩展名：.png,.jpg,.jpeg</div>
            </div>
          </Upload>
        </Item>
        <Item label='内容' name='content'>
          <Editor />
        </Item>
      </Form>
    </Modal>
  )
}

export default Main
